package com.jpyl.jpMedicalTreatment.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ToggleButton;


import com.forxindu.kit.box.JavaKit;
import com.forxindu.kit.box.VerifyKit;
import com.forxindu.kit.box.ViewKit;
import com.google.gson.JsonObject;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.common.MedicalSettings;
import com.jpyl.jpMedicalTreatment.model.ErrorMessageModel;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.model.RxSpf_UserModel;
import com.jpyl.jpMedicalTreatment.model.UserMessageModel;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;

import butterknife.BindView;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 登陆界面
 * 患者：15102266645 密码：1
 * 总经销商：1860000010 密码：0010
 * 医生：1860000002 密码1
 * 代理商： 1860000001 密码1
 * Created by 521546564465 on 2018/11/9.
 */

public class LoginActivity extends BaseActivity {

    @BindView(R.id.login_name)
    EditText loginName;

    @BindView(R.id.login_password)
    EditText password;

    @BindView(R.id.login_password_encrypt)
    ToggleButton passwordEncrypt;

    @BindView(R.id.login_find_password)
    TextView findPassword;

    @BindView(R.id.login_btn)
    Button loginButton;

    @BindView(R.id.register_btn)
    TextView registerButton;

    @BindView(R.id.local_version)
    TextView localVersion;

    public static Activity activity;
    private RxSpf_UserModel spfUserModel;

    private String patient = "patient";//==1患者登陆可见
    private String doctor = "doctor";// ==2医生登陆可见
    private String agent = "agent";// ==3代理可见
    private String area_agent = "area_agent";// ==4总代理可见(总经销商)
    private int userFlag;

    @Override
    protected int getLayoutId() {
        return R.layout.common_login_layout;
    }

    @Override
    public void afterCreate(Bundle savedInstanceState) {
        activity = this;
        setToolBarEnabled(false);
        spfUserModel = RxSpf_UserModel.create(this);
        localVersion.setText("V " + getVersionName());
        loginName.setText(spfUserModel.loginname().get());
        password.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                setLoginButtonStatus();
            }
        });
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
        findPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, FindPasswordActivity.class);
                startActivity(intent);
            }
        });
        loginButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (JavaKit.isStringEmpty(loginName.getText().toString())) {
                    ViewKit.showToast(LoginActivity.this, getString(R.string.login_name));
                    return;
                }
                if (!VerifyKit.isMobile(loginName.getText().toString())) {
                    ViewKit.showToast(LoginActivity.this, getString(R.string
                            .find_password_correct_mobile));
                    return;
                }
                if (JavaKit.isStringEmpty(password.getText().toString())) {
                    ViewKit.showToast(LoginActivity.this, getString(R.string.login_password));
                    return;
                }
//                if (password.getText().toString().length() < 6) {
//                    ViewKit.showToast(LoginActivity.this, "密码不能少于6位");
//                    return;
//                }
                login();
            }
        });

        passwordEncrypt.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        if (Build.VERSION.SDK_INT >= 23) {
            showContacts();
        }
    }

    private void setLoginButtonStatus() {

        if (loginName.getText().toString().length() >= 11 && password.getText().toString().length
                () >= 6) {
            loginButton.setBackgroundResource(R.drawable.round_corner_dark_blue_bg_shape10);
        } else {
            loginButton.setBackgroundResource(R.drawable.round_corner_blue_bg_shape10);
        }
    }

    final RequestApi publicApi = Network.getRequestApi();

    /**
     * 登录
     * param
     */
    private void login() {
        String loginNames = loginName.getText().toString();
        String passwords = password.getText().toString();
        final JsonObject body = new JsonObject();
        body.addProperty("province", "天津");

        publicApi.login(loginNames, passwords, body.toString()).map(new Func1<ResponseModel<UserMessageModel>,
                UserMessageModel>() {
            @Override
            public UserMessageModel call(ResponseModel<UserMessageModel> responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<UserMessageModel>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                            ViewKit.showToast(LoginActivity.this, error.getMessageModel().getMsg());
                        }
                    }

                    @Override
                    public void onNext(UserMessageModel userModel) {
                        spfUserModel.userId().put(userModel.getUser().getId());
                        spfUserModel.sid().put(userModel.getSession().getSid());
                        spfUserModel.expireDate().put(userModel.getSession().getExpireDate());
                        spfUserModel.loginname().put(userModel.getUser().getLoginname());
                        spfUserModel.username().put(userModel.getUser().getUsername());
                        spfUserModel.address().put(userModel.getUser().getAddress());
                        spfUserModel.phone().put(userModel.getUser().getPhone());
                        spfUserModel.point().put(userModel.getUser().getPoint());
                        if (patient.equals(userModel.getType())) {
                            //患者
                            userFlag = MedicalSettings.USERTYPE_PATIENT;
                            spfUserModel.doctorId().put(userModel.getUser().getDoctor().getId());
                            spfUserModel.doctorName().put(userModel.getUser().getDoctor()
                                    .getUsername
                                    ());
                        } else if (doctor.equals(userModel.getType())) {
                            //医生
                            userFlag = MedicalSettings.USERTYPE_DOCTOR;

                        } else if (agent.equals(userModel.getType())) {
                            //代理
                            userFlag = MedicalSettings.USERTYPE_AGENT;
                        } else {
                            //总代理
                            userFlag = MedicalSettings.USERTYPE_GENERALAGENT;
                        }
                        spfUserModel.type().put(userFlag + "");

                        startActivity(new Intent(getApplicationContext(), HomeActivity.class)
                                .putExtra(MedicalSettings.STRUSERTYPE, userFlag));
                        finish();
                    }
                });
    }

    public void showContacts() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission
                .READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.SET_DEBUG_APP)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_LOGS)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
                    .WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW,
                    Manifest.permission.GET_ACCOUNTS
                    , Manifest.permission.READ_LOGS}, MedicalSettings.BAIDU_READ_PHONE_STATE);
        }
    }

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case MedicalSettings.BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    // 没有获取到权限，做特殊处理
                    ViewKit.showToast(this, "获取位置权限失败，请手动开启");
                }
                break;
            default:
                break;
        }
    }
}
